package com.yunform.framework.util.jxls;


import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
/**
* 利用POI实现向excel中写入内容
*/
public class ExcelWriter {


public static void write(String sheetName,List<String> headers,List<Object[]> rows,OutputStream outputStream) throws Exception{
	HSSFWorkbook workbook = new HSSFWorkbook();
	HSSFSheet sheet = workbook.createSheet(sheetName);
	int rowNum = 0;
	/**
	 * 写标题
	 */
	HSSFRow headerRow = sheet.createRow(rowNum); rowNum++;
	for(int i=0;i<headers.size(); i++){
		HSSFCell cell = headerRow.createCell((short) i);
		cell.setCellType(HSSFCell.CELL_TYPE_STRING);
		HSSFRichTextString nameContent = new HSSFRichTextString(headers.get(i));
		cell.setCellValue(nameContent);
	}
	
//	HSSFCell id = row.createCell((short) 0);
//	id.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
//	HSSFRichTextString idContent = new HSSFRichTextString("用户id号");
//	id.setCellValue(idContent);
//	HSSFCell name = row.createCell((short) 1);
//	name.setCellType(HSSFCell.CELL_TYPE_STRING);
//	HSSFRichTextString nameContent = new HSSFRichTextString("用户名");
//	name.setCellValue(nameContent);
//	HSSFCell password = row.createCell((short) 2);
//	password.setCellType(HSSFCell.CELL_TYPE_STRING);
//	HSSFRichTextString passwordContent = new HSSFRichTextString("用户密码");
//	password.setCellValue(passwordContent);
	
	/**
	 * 写记录
	 */
	for(Object[] dataRow : rows){
		HSSFRow appendRow = sheet.createRow(rowNum); rowNum++;
		for(int i =0; i<dataRow.length; i++){
			HSSFCell cell = appendRow.createCell((short) i);
			cell.setCellType(HSSFCell.CELL_TYPE_STRING);
			HSSFRichTextString nameContent = new HSSFRichTextString(String.valueOf(dataRow[i]));
			cell.setCellValue(nameContent);
		}
	}
//	// 新建一输出文件流
//	FileOutputStream out = new FileOutputStream(fileToWrite);
	// 把相应的Excel 工作簿存盘
	workbook.write(outputStream);
	outputStream.flush();
	// 操作结束，关闭文件
	outputStream.close();
}

public static void main(String[] args) throws Exception {
		// 新建一输出文件流
		FileOutputStream outputStream = new FileOutputStream("c:/test.xls");
		// 把相应的Excel 工作簿存盘
		List<Object[]> rows = new ArrayList<Object[]>();
		Object[] row = new Object[]{"aaa,","b"};
		rows.add(row);
		row = new Object[]{"bbb,","a"};
		rows.add(row);
		
		new ExcelWriter().write("第一页", Arrays.asList(new String[]{"t1","t2"}), rows, outputStream);
}
}
